package com.ktg.mes.md.controller;

import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.mes.md.domain.MesScalesOrder;
import com.ktg.mes.md.service.IMesScalesOrderService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.md.domain.MesScalesOrderItem;
import com.ktg.mes.md.service.IMesScalesOrderItemService;
import com.ktg.common.utils.poi.ExcelUtil;


/**
 * 销售订单产品Controller
 *
 * @author byteco
 * @date 2022-09-03
 */
@RestController
@RequestMapping("/md/mesScalesOrderItem")
public class MesScalesOrderItemController extends BaseController
{
    @Autowired
    private IMesScalesOrderItemService mesScalesOrderItemService;

    @Autowired
    private IMesScalesOrderService mesScalesOrderService;




    /**
     * 查询销售订单产品列表
     */
    @PreAuthorize("@ss.hasPermi('md:mesScalesOrderItem:list')")
    @GetMapping("/list")
    public Result<IPage<MesScalesOrderItem>> list(MesScalesOrderItem mesScalesOrderItem,
                                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                  HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询销售订单产品列表",req,null);
        try {
            Page<MesScalesOrderItem> page = new Page<MesScalesOrderItem>(pageNo, pageSize);
            QueryWrapper<MesScalesOrderItem> lqw = new QueryWrapper<>(mesScalesOrderItem);
            lqw.orderByDesc("create_time");
            lqw.ge("count_surplus",0.1);
            IPage<MesScalesOrderItem> pageList = mesScalesOrderItemService.page(page, lqw);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 导出销售订单产品列表
     */
    @PreAuthorize("@ss.hasPermi('md:mesScalesOrderItem:export')")
    @Log(title = "销售订单产品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MesScalesOrderItem mesScalesOrderItem,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出销售订单产品列表",req,mesScalesOrderItem);
        try {
            List<MesScalesOrderItem> list = mesScalesOrderItemService.queryList(mesScalesOrderItem);
            ExcelUtil<MesScalesOrderItem> util = new ExcelUtil<MesScalesOrderItem>(MesScalesOrderItem.class);
            util.exportExcel(response, list, "销售订单产品数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取销售订单产品详细信息
     */
    @PreAuthorize("@ss.hasPermi('md:mesScalesOrderItem:query')")
    @GetMapping(value = "/{scalesOrderItemId}")
    public Result<MesScalesOrderItem> getInfo(@PathVariable("scalesOrderItemId") String scalesOrderItemId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取销售订单产品详细信息",req,null);
        try {
            return apiLog.ok(mesScalesOrderItemService.getInfo(scalesOrderItemId));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增销售订单产品
     */
    @PreAuthorize("@ss.hasPermi('md:mesScalesOrderItem:add')")
    @Log(title = "销售订单产品", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<String> add(@RequestBody MesScalesOrderItem mesScalesOrderItem,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增销售订单产品",req,mesScalesOrderItem);
        try {
            MesScalesOrder scalesOrder = mesScalesOrderService.getInfo(mesScalesOrderItem.getScalesOrderId());

            QueryWrapper<MesScalesOrderItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scales_order_id",mesScalesOrderItem.getScalesOrderId());
            queryWrapper.orderByDesc("scales_order_item_code");
            queryWrapper.last("limit 1");
            MesScalesOrderItem lastTtem =  mesScalesOrderItemService.getOne(queryWrapper);

            int index = 1;
            if (lastTtem != null && lastTtem.getScalesOrderItemCode() != null){
                String[] codeList = lastTtem.getScalesOrderItemCode().split("R");
                if (codeList.length > 1){
                    index = Integer.valueOf(codeList[1]).intValue();
                    index++;
                }
            }
            mesScalesOrderItem.setScalesOrderItemCode(scalesOrder.getScalesOrderCode()+"R"+index);
            mesScalesOrderItem.setClientId(scalesOrder.getClientId());
            mesScalesOrderItem.setClientCode(scalesOrder.getClientCode());
            mesScalesOrderItem.setClientName(scalesOrder.getClientName());
            mesScalesOrderItem.setCountSurplus(mesScalesOrderItem.getQuantity());
            mesScalesOrderItemService.insert(mesScalesOrderItem);
            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    /**
     * 修改销售订单产品
     */
    @PreAuthorize("@ss.hasPermi('md:mesScalesOrderItem:edit')")
    @Log(title = "销售订单产品", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result<String> edit(@RequestBody MesScalesOrderItem mesScalesOrderItem,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改销售订单产品",req,mesScalesOrderItem);
        try {
            MesScalesOrderItem orderItem = mesScalesOrderItemService.getById(mesScalesOrderItem.getScalesOrderItemId());

            double ss = 0;
            if (mesScalesOrderItem.getCountScheduling() != null){
                ss = mesScalesOrderItem.getCountScheduling().doubleValue();
                ss = mesScalesOrderItem.getQuantity().doubleValue() - ss;
            }
            mesScalesOrderItem.setCountSurplus(BigDecimal.valueOf(ss));
            mesScalesOrderItemService.update(mesScalesOrderItem);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除销售订单产品
     */
    @PreAuthorize("@ss.hasPermi('md:mesScalesOrderItem:remove')")
    @Log(title = "销售订单产品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{scalesOrderItemIds}")
    public Result<String> remove(@PathVariable String[] scalesOrderItemIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除销售订单产品",req,null);
        try {
            mesScalesOrderItemService.delete(scalesOrderItemIds);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
